<?php

namespace app\common\library;

use app\common\model\order\Order;
use think\Env;
use wechatPay\Wxpay;

/**
 * 统一退款
 */
class Refund
{
    //快递100授权码
    //退款
    public static function refund($id)
    {

        //商户订单号,微信生成的退款订单号 二选一即可
        $order = Order::get($id);
        if (Env::get('app.debug') == true) {
            $order['pay_money'] = 0.01;
        }
        $time = time();
        $out_refund_no = sn('order', 'out_refund_no', 'RF');
        $refundData = [
            'out_refund_no' => $out_refund_no,
            'reason' => '商品退款',

            'notify_url' => cdnurl(config('site.refund_notify'), true),
            'funds_account' => 'AVAILABLE',
            'amount' => [
                'refund' => floatval($order['pay_money']) * 100, //退款标价金额，单位为分，可以做部分退款
                'total' => floatval($order['pay_money']) * 100, //订单总金额，单位为分
                'currency' => 'CNY'
            ]
        ];
        $refundData['transaction_id'] = $order['transaction_id'];
        $url = 'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds';
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $mchid = config('site.mch_id'); //商户ID
        $xlid = config('site.serial_no'); //证书序列号

        $refundData = json_encode($refundData);
        $nonce = Wxpay::getNonceStr();
        $key = Wxpay::getSign($refundData, $urlarr['path'], $nonce, $time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $nonce, $time, $key);
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );
        $res = Wxpay::curl_post_https($url, $refundData, $header);
        $res_array = json_decode($res, true);
        if (isset($res_array['status']) && ($res_array['status'] == 'PROCESSING' || $res_array['status'] == 'SUCCESS') && isset($res_array['status'])) {
        } else {
            exception($res_array['message']);
        }
    }
}
